package com.wlcb.jpower.chat.message.handler;

import com.wlcb.jpower.chat.reply.ReplyContext;
import com.wlcb.jpower.chat.reply.ReplyEntity;
import com.wlcb.jpower.constant.ChatConfigConstant;
import com.wlcb.jpower.constant.ChatConstant;
import com.wlcb.jpower.im.cache.ImChatRecordCache;
import com.wlcb.jpower.im.model.DataPacket;
import com.wlcb.jpower.module.common.utils.Fc;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Component;

import java.util.Map;

import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType;

/**
 * 上报地理位置事件 和 接收地理位置消息
 */
@Component
public class LocationHandler extends AbstractHandler {

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) {
        String appId = context.get("appId").toString();
        if (wxMessage.getMsgType().equals(XmlMsgType.LOCATION)) {
            DataPacket dataPacket = toDataPacket(wxMessage, appId);
            try {
                dataPacket.setContent("定位信息");
                ReplyContext replyContext = ReplyContext.getInstance(dataPacket, wxMessage, ImChatRecordCache.getInstance(wxMessage.getFromUser()));
                ReplyEntity replyEntity = replyContext.reply();
                if (Fc.notNull(replyEntity)) {
                    replyEntity.sendReply();
                } else {
                    replyContext.forwardKefu();
                }
            } catch (Exception e) {
                this.logger.error("位置消息接收处理失败", e);
                return null;
            }
        }

        //上报地理位置事件
        this.logger.debug("上报地理位置，纬度 : {}，经度 : {}，精度 : {}",
                wxMessage.getLatitude(), wxMessage.getLongitude(), String.valueOf(wxMessage.getPrecision()));
        return null;
    }

    private DataPacket toDataPacket(WxMpXmlMessage wxMessage, String appId) {
        System.out.println(wxMessage.toString());
        DataPacket dataPacket = new DataPacket();
        dataPacket.setAction(ChatConstant.ChatActionEnum.CUSTOMER_USER_MESSAGE.type);
        dataPacket.setSendId(wxMessage.getFromUser());
        dataPacket.setReceiveType(ChatConfigConstant.UserType.CUSTOMER);
        dataPacket.setSendType(ChatConfigConstant.UserType.OTHER);
        dataPacket.setDate(System.currentTimeMillis());
        dataPacket.setAppId(appId);
        dataPacket.setType(ChatConstant.MessageTypeEnum.TEXT.type);
        Double x = wxMessage.getLocationX();
        Double y = wxMessage.getLocationY();
        String label = wxMessage.getLabel();
        dataPacket.setContent("收到用户发送的位置消息, 位置:" + label + ", 经度：" + y + ", 维度：" + x);
        return dataPacket;
    }
}
